#include "usart.h"
#include <string.h>

/* 重定向printf函数 */
int fputc(int ch, FILE *f)
{
    usart_data_transmit(USART0, (uint8_t)ch);//发送数据
    while(RESET == usart_flag_get(USART0, USART_FLAG_TBE));//等待发送标志位非零
    return ch;
}

void USART0_Init(uint32_t baudrate)//串口0初始化
{
	uint8_t Res = 0;
    rcu_periph_clock_enable(RCU_GPIOA);//打开GPIOA时钟
    rcu_periph_clock_enable(RCU_USART0);//打开串口0时钟
    
    gpio_init(GPIOA,GPIO_MODE_AF_PP,GPIO_OSPEED_50MHZ,GPIO_PIN_9);//TX
    gpio_init(GPIOA,GPIO_MODE_IN_FLOATING,GPIO_OSPEED_50MHZ,GPIO_PIN_10);//RX  

    usart_baudrate_set( USART0,  baudrate);//波特率
    usart_parity_config( USART0,  USART_PM_NONE);//无检验位
    usart_word_length_set( USART0,  USART_WL_8BIT);//8位字长
    usart_stop_bit_set( USART0,  USART_STB_1BIT);//1个停止位
    usart_hardware_flow_rts_config(USART0, USART_RTS_DISABLE);//硬件流控制
    usart_hardware_flow_cts_config(USART0, USART_CTS_DISABLE);//硬件流控制
    
    usart_transmit_config( USART0,  USART_TRANSMIT_ENABLE);//发送使能
    usart_receive_config( USART0,  USART_RECEIVE_ENABLE);//接收使能
	
    usart_interrupt_enable( USART0, USART_INT_RBNE);//接收中断使能
	//usart_interrupt_enable(USART0, USART_INT_IDLE);//接收空闲中断使能
    
    nvic_irq_enable(USART0_IRQn,2, 2);//设置优先级
    usart_enable(USART0);//打开串口
}

uint8_t buff[LEN]={0}; //接收缓冲
uint8_t flag = 0;//接收标志位
uint16_t i = 0;
uint8_t cmd = 0;//命令
uint8_t sum = 0;//检验和

void USART0_IRQHandler(void)//串口接收中断
{
    uint16_t data = 0;//临时变量

    if(usart_flag_get(USART0,USART_FLAG_RBNE) != RESET)
    {
        usart_flag_clear(USART0,USART_FLAG_RBNE);
        usart_interrupt_flag_clear(USART0,USART_INT_RBNE);
        data = usart_data_receive(USART0);//读数据存到临时变量
		buff[i]=data;
		i++;
        
		if(buff[0] != 0xAA)//帧头
		{
			i = 0;
		}
		
		cmd = buff[1];//命令
		sum = buff[2];//检验和
		
		if(sum == (0xAA+cmd))//检验和
		{
			i = 0;
			buff[0] = 0xFF;buff[1] = 0xFF;buff[2] = 0xFF;
			flag = 0xFF;
		}
    }
}

